package manager

import (
	"BlazeRider-backend/config"
	"database/sql"
	"fmt"
	"sync"
)

// ClientErrorRecordManager 管理礼物赠送记录
type GiftRecordManager struct {
	roomGiftRecords map[string]map[string][]GiftRecord
	storage         GiftRecordMysqlStorage
	mu              sync.Mutex
}

// GiftRecord 表示单个礼物的赠送记录
type GiftRecord struct {
	MsgId         string       `json:"msg_id"`
	LiveRoomId    string       `json:"live_room_id"`
	Times         int          `json:"times"`
	Track         int          `json:"track"`
	UserId        string       `json:"user_id"`
	GiftId        string       `json:"gift_id"`
	GiftName      string       `json:"gift_name"`
	Amount        int          `json:"amount"`
	Value         int          `json:"value"`
	TotalValue    int          `json:"total_value"`
	Score         int          `json:"score"`
	TotalScore    int          `json:"total_score"`
	GiftLevel     int          `json:"gift_level"`
	GiftUpgrading int          `json:"gift_upgrading"`
	CreateAt      sql.NullTime `json:"create_at"` // 使用 NullTime
	UpdateAt      sql.NullTime `json:"update_at"` // 使用 NullTime
}

// GiftRecord 表示单个礼物的赠送记录与用户相关联的数据
type GiftRecordWithUserInfo struct {
	MsgId         string       `json:"msg_id"`
	LiveRoomId    string       `json:"live_room_id"`
	Times         int          `json:"times"`
	Track         int          `json:"track"`
	Job           int          `json:"job"`
	UserId        string       `json:"user_id"`
	GiftId        string       `json:"gift_id"`
	GiftName      string       `json:"gift_name"`
	Amount        int          `json:"amount"`
	Value         int          `json:"value"`
	TotalValue    int          `json:"total_value"`
	Score         int          `json:"score"`
	TotalScore    int          `json:"total_score"`
	GiftLevel     int          `json:"gift_level"`
	GiftUpgrading int          `json:"gift_upgrading"`
	UserName      string       `json:"user_name"`
	UserHeadImg   string       `json:"head_img"`
	UserLevel     int          `json:"level"`
	UserScore     int          `json:"score"`
	ExpireAt      sql.NullTime `json:"expire_at"`
	CreateAt      sql.NullTime `json:"create_at"` // 使用 NullTime
	UpdateAt      sql.NullTime `json:"update_at"` // 使用 NullTime
}

func NewGiftRecordManager() *GiftRecordManager {
	var storage *GiftRecordMysqlStorage
	var err error
	if config.Get().Database.Enabled {
		storage, err = NewGiftRecordMysqlStorage()
		if err != nil {
			return nil
		}

		return &GiftRecordManager{
			storage: *storage,
		}
	}
	return &GiftRecordManager{
		roomGiftRecords: make(map[string]map[string][]GiftRecord),
	}
}

// 查询本局最后一次该礼物信息
func (grm *GiftRecordManager) GetGiftRecordByMsgId(msgID string) (*GiftRecord, error) {
	if config.Get().Database.Enabled {
		giftRecordMysqlInfo, err := grm.storage.GetGiftRecordByMsgId(msgID)
		if err != nil {
			return nil, err
		}

		return &GiftRecord{
			MsgId:         giftRecordMysqlInfo.MsgId,
			LiveRoomId:    giftRecordMysqlInfo.LiveRoomId,
			Times:         giftRecordMysqlInfo.Times,
			UserId:        giftRecordMysqlInfo.UserId,
			GiftId:        giftRecordMysqlInfo.GiftId,
			GiftName:      giftRecordMysqlInfo.GiftName,
			Amount:        giftRecordMysqlInfo.Amount,
			Value:         giftRecordMysqlInfo.OneValue,
			TotalValue:    giftRecordMysqlInfo.TotalValue,
			Score:         giftRecordMysqlInfo.Score,
			TotalScore:    giftRecordMysqlInfo.TotalScore,
			GiftLevel:     giftRecordMysqlInfo.GiftLevel,
			GiftUpgrading: giftRecordMysqlInfo.GiftUpgrading,
			CreateAt:      giftRecordMysqlInfo.CreateAt,
			UpdateAt:      giftRecordMysqlInfo.UpdateAt,
		}, nil // 返回 LiveRoomStatus 和 false
	}
	return nil, fmt.Errorf("GetGiftRecordByMsgId no mem logic")
}

// AddGiftRecord 增加礼物赠送记录
func (grm *GiftRecordManager) AddGiftRecord(msgID, liveRoomID, userID, giftID, giftName string, giftValue, giftScore, amount, times, giftLevel, giftUpgrading, track, job int) error {
	if config.Get().Database.Enabled {
		err := grm.storage.AddGiftRecord(msgID, liveRoomID, userID, giftID, giftName, giftValue, giftScore, amount, times, giftLevel, giftUpgrading, track, job)
		if err != nil {
			return err
		}
		return nil
	}
	grm.mu.Lock()
	defer grm.mu.Unlock()

	userRecords, exists := grm.roomGiftRecords[liveRoomID]
	if !exists {
		userRecords = make(map[string][]GiftRecord)
		grm.roomGiftRecords[liveRoomID] = userRecords
	}

	userRecords[userID] = append(userRecords[userID], GiftRecord{
		UserId: userID,
		GiftId: giftID,
		Amount: 1,
		Value:  giftValue,
	})
	return nil
}

// 查询本局最后一次该礼物信息
func (grm *GiftRecordManager) GetLastGiftRecordByUserIdAndGiftId(liveRoomID string, times int, userId string, gift_id string) (*GiftRecord, error) {
	if config.Get().Database.Enabled {
		giftRecordMysqlInfo, err := grm.storage.GetLastGiftRecordByUserIdAndGiftId(liveRoomID, times, userId, gift_id)
		if err != nil {
			return nil, err
		}

		return &GiftRecord{
			MsgId:         giftRecordMysqlInfo.MsgId,
			LiveRoomId:    giftRecordMysqlInfo.LiveRoomId,
			Times:         giftRecordMysqlInfo.Times,
			UserId:        giftRecordMysqlInfo.UserId,
			GiftId:        giftRecordMysqlInfo.GiftId,
			GiftName:      giftRecordMysqlInfo.GiftName,
			Amount:        giftRecordMysqlInfo.Amount,
			Value:         giftRecordMysqlInfo.OneValue,
			TotalValue:    giftRecordMysqlInfo.TotalValue,
			Score:         giftRecordMysqlInfo.Score,
			TotalScore:    giftRecordMysqlInfo.TotalScore,
			GiftLevel:     giftRecordMysqlInfo.GiftLevel,
			GiftUpgrading: giftRecordMysqlInfo.GiftUpgrading,
			CreateAt:      giftRecordMysqlInfo.CreateAt,
			UpdateAt:      giftRecordMysqlInfo.UpdateAt,
		}, nil // 返回 LiveRoomStatus 和 false
	}
	return nil, fmt.Errorf("GetLastGiftRecordByUserIdAndGiftId no mem logic")
}

// GetGiftCountByUser 获取指定用户在某个直播间内赠送的礼物数量
func (grm *GiftRecordManager) GetGiftCountByUserAndGiftId(liveRoomID string, times int, userID, giftId string) (int, error) {
	if config.Get().Database.Enabled {
		var sumAmount int
		sumAmount, err := grm.storage.GetGiftCountByUserAndGiftId(liveRoomID, times, userID, giftId)
		if err != nil {
			return 0, err
		}

		return sumAmount, nil // 返回 LiveRoomStatus 和 false
	}

	grm.mu.Lock()
	defer grm.mu.Unlock()

	userRecords, exists := grm.roomGiftRecords[liveRoomID]
	if !exists {
		return 0, fmt.Errorf("can not find the gift record")
	}

	var totalCount int
	for _, records := range userRecords {
		for _, record := range records {
			if record.UserId == userID && record.GiftId == giftId {
				totalCount += record.Amount
			}
		}
	}
	return totalCount, nil
}

// GetTotalScoreByRoomId 获取某场比赛的总积分
func (grm *GiftRecordManager) GetTotalScoreByRoomId(liveRoomID string, times int) (int, error) {
	if config.Get().Database.Enabled {
		var sumScore int
		sumScore, err := grm.storage.GetTotalScoreByRoomId(liveRoomID, times)
		if err != nil {
			return 0, err
		}

		return sumScore, nil // 返回 LiveRoomStatus 和 false
	}

	grm.mu.Lock()
	defer grm.mu.Unlock()

	userRecords, exists := grm.roomGiftRecords[liveRoomID]
	if !exists {
		return 0, fmt.Errorf("can not find the gift record")
	}

	var totalScore int
	for _, records := range userRecords {
		for _, record := range records {
			totalScore += record.TotalScore
		}
	}
	return totalScore, nil
}

// GetGiftRecordByLiveRoomAndTimes 获取某个直播间内赠送的礼物数据
func (grm *GiftRecordManager) GetGiftRecordByLiveRoomAndTimes(liveRoomID string, times int) ([]GiftRecord, error) {
	var giftRecords []GiftRecord

	if config.Get().Database.Enabled {
		// 调用 MySQL 存储层的方法
		giftRecordInfos, err := grm.storage.GetGiftRecordByLiveRoomAndTimes(liveRoomID, times)
		if err != nil {
			return nil, err
		}

		// 将 GiftRecordMysqlInfo 转换为 GiftRecord
		for _, recordInfo := range giftRecordInfos {
			giftRecord := GiftRecord{
				MsgId:         recordInfo.MsgId,
				LiveRoomId:    recordInfo.LiveRoomId,
				Times:         recordInfo.Times,
				Track:         recordInfo.Track,
				UserId:        recordInfo.UserId,
				GiftId:        recordInfo.GiftId,
				GiftName:      recordInfo.GiftName,
				Amount:        recordInfo.Amount,
				Value:         recordInfo.OneValue, // 假设 Value 对应 OneValue
				TotalValue:    recordInfo.TotalValue,
				Score:         recordInfo.Score,
				TotalScore:    recordInfo.TotalScore,
				GiftLevel:     recordInfo.GiftLevel,
				GiftUpgrading: recordInfo.GiftUpgrading,
				CreateAt:      recordInfo.CreateAt,
				UpdateAt:      recordInfo.UpdateAt,
			}
			giftRecords = append(giftRecords, giftRecord)
		}

		return giftRecords, nil
	}

	// 如果 MySQL 未启用，返回错误
	return giftRecords, fmt.Errorf("database is not enabled")
}

// GetGiftRecordWithUserInfoByLiveRoomAndTimes 获取在某个直播间内赠送的礼物加用户的数据
func (grm *GiftRecordManager) GetGiftRecordWithUserInfoByLiveRoomAndTimes(liveRoomID string, times int) ([]GiftRecordWithUserInfo, error) {
	var giftRecordsWithUserInfo []GiftRecordWithUserInfo

	if config.Get().Database.Enabled {
		// 调用 MySQL 存储层的方法
		giftRecordInfos, err := grm.storage.GetGiftRecordWithUserInfoByLiveRoomAndTimes(liveRoomID, times)
		if err != nil {
			return nil, err
		}

		// 将 GiftRecordMysqlInfo 转换为 GiftRecord
		for _, recordInfo := range giftRecordInfos {
			giftRecordWithUserInfo := GiftRecordWithUserInfo{
				MsgId:         recordInfo.MsgId,
				LiveRoomId:    recordInfo.LiveRoomId,
				Times:         recordInfo.Times,
				Track:         recordInfo.Track,
				Job:           recordInfo.Job,
				UserId:        recordInfo.UserId,
				GiftId:        recordInfo.GiftId,
				GiftName:      recordInfo.GiftName,
				Amount:        recordInfo.Amount,
				Value:         recordInfo.OneValue, // Value 对应 单个礼物的value
				TotalValue:    recordInfo.TotalValue,
				Score:         recordInfo.Score,
				TotalScore:    recordInfo.TotalScore,
				GiftLevel:     recordInfo.GiftLevel,
				GiftUpgrading: recordInfo.GiftUpgrading,
				UserName:      recordInfo.UserName,
				UserHeadImg:   recordInfo.UserHeadImg,
				UserLevel:     recordInfo.UserLevel,
				UserScore:     recordInfo.UserScore,
				ExpireAt:      recordInfo.ExpireAt,
				CreateAt:      recordInfo.CreateAt,
				UpdateAt:      recordInfo.UpdateAt,
			}
			giftRecordsWithUserInfo = append(giftRecordsWithUserInfo, giftRecordWithUserInfo)
		}

		return giftRecordsWithUserInfo, nil
	}

	// 如果 MySQL 未启用，返回错误
	return giftRecordsWithUserInfo, fmt.Errorf("database is not enabled")
}

// GetGiftRecordWithUserInfoByLiveRoomAndTimesByTime 获取在某个直播间某个时间点后赠送的礼物加用户的数据
func (grm *GiftRecordManager) GetGiftRecordWithUserInfoByLiveRoomAndTimesByTime(liveRoomID string, times int, timeStr string) ([]GiftRecordWithUserInfo, error) {
	var giftRecordsWithUserInfo []GiftRecordWithUserInfo

	if config.Get().Database.Enabled {
		// 调用 MySQL 存储层的方法
		giftRecordInfos, err := grm.storage.GetGiftRecordWithUserInfoByLiveRoomAndTimesByTime(liveRoomID, times, timeStr)
		if err != nil {
			return nil, err
		}

		// 将 GiftRecordMysqlInfo 转换为 GiftRecord
		for _, recordInfo := range giftRecordInfos {
			giftRecordWithUserInfo := GiftRecordWithUserInfo{
				MsgId:         recordInfo.MsgId,
				LiveRoomId:    recordInfo.LiveRoomId,
				Times:         recordInfo.Times,
				Track:         recordInfo.Track,
				UserId:        recordInfo.UserId,
				GiftId:        recordInfo.GiftId,
				GiftName:      recordInfo.GiftName,
				Amount:        recordInfo.Amount,
				Value:         recordInfo.OneValue, // Value 对应 单个礼物的value
				TotalValue:    recordInfo.TotalValue,
				Score:         recordInfo.Score,
				TotalScore:    recordInfo.TotalScore,
				GiftLevel:     recordInfo.GiftLevel,
				GiftUpgrading: recordInfo.GiftUpgrading,
				UserName:      recordInfo.UserName,
				UserHeadImg:   recordInfo.UserHeadImg,
				UserLevel:     recordInfo.UserLevel,
				UserScore:     recordInfo.UserScore,
				ExpireAt:      recordInfo.ExpireAt,
				CreateAt:      recordInfo.CreateAt,
				UpdateAt:      recordInfo.UpdateAt,
			}
			giftRecordsWithUserInfo = append(giftRecordsWithUserInfo, giftRecordWithUserInfo)
		}

		return giftRecordsWithUserInfo, nil
	}

	// 如果 MySQL 未启用，返回错误
	return giftRecordsWithUserInfo, fmt.Errorf("database is not enabled")
}

// GetAccScoreByRoomIdAndUserId 获取某场比赛的总积分
func (grm *GiftRecordManager) GetAccScoreByRoomIdAndUserId(liveRoomID string, times int, userId string) (int, error) {
	if config.Get().Database.Enabled {
		var accScore int
		accScore, err := grm.storage.GetAccScoreByRoomIdAndUserId(liveRoomID, times, userId)
		if err != nil {
			return 0, err
		}

		return accScore, nil // 返回 LiveRoomStatus 和 false
	}

	// 如果 MySQL 未启用，返回错误
	return 0, fmt.Errorf("database is not enabled")
}

func (grm *GiftRecordManager) SetGiftRecordLevel(msgId string, giftLevel, giftUpgrading int) error {
	if config.Get().Database.Enabled {
		err := grm.storage.SetGiftRecordLevel(msgId, giftLevel, giftUpgrading)
		if err != nil {
			return err
		}

		return nil // 返回 LiveRoomStatus 和 false
	}

	return fmt.Errorf("SetGiftRecordLevel no mem logic")
}

// RemoveLiveRoomRecords 删除指定直播间的所有礼物记录
func (grm *GiftRecordManager) RemoveLiveRoomRecords(liveRoomID string) {
	grm.mu.Lock()
	defer grm.mu.Unlock()

	delete(grm.roomGiftRecords, liveRoomID)
}
